package com.tbit.uqbike.client.service.impl;

import com.tbit.uqbike.client.constant.AccountConfigExtConstant;
import com.tbit.uqbike.client.constant.AdaPayConstant;
import com.tbit.uqbike.client.dao.core.UserDivideDao;
import com.tbit.uqbike.client.pojo.Account;
import com.tbit.uqbike.client.pojo.Machine;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.pojo.newEntity.UserDivide;
import com.tbit.uqbike.client.pojo.newEntity.UserDivideVo;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 8:46 2022/5/16
 */
@Service
public class UserDivideServiceImpl implements UserDivideService {

    @Autowired
    private UserDivideDao userDivideDao;
    @Resource
    private MachineService machineService;
    @Resource
    private AdaPayService adaPayService;
    @Resource
    private CacheService cacheService;
    @Resource
    private AccountService accountService;

    @Override
    public List<UserDivide> getByAccountId(Integer accountId) {
        /**获取分账的账号是否存在需要切换*/
        List<UserDivide> userDivides = userDivideDao.getByAccountId(accountId);
        if (userDivides.size() > 0) {
            /**查询当前正在使用的分账账号信息，需要置成已失效*/
            List<UserDivide> expireDivides = getByAccountIdAndState(accountId, AdaPayConstant.ADAPAY_USER_DIVIDE_USED);
            /**需要更新为已到期的id*/
            List<Integer> expireIds = new ArrayList<>();
            expireDivides.forEach(e -> {
                expireIds.add(e.getId());
            });
            userDivideDao.edit(new UserDivideVo(AdaPayConstant.ADAPAY_USER_DIVIDE_EXPIRE, StringUtil.getListString(expireIds)));
            /**需要更新为在使用的id*/
            List<Integer> useIds = new ArrayList<>();
            userDivides.forEach(e -> {
                useIds.add(e.getId());
            });
            userDivideDao.edit(new UserDivideVo(AdaPayConstant.ADAPAY_USER_DIVIDE_USED, StringUtil.getListString(useIds)));
            return userDivides;
        } else {
            return getByAccountIdAndState(accountId, AdaPayConstant.ADAPAY_USER_DIVIDE_USED);
        }
    }

    /**
     * 分账比例获取
     * 存在车辆分账比例 ， 则取车辆分账比例
     * 否则取区域分账比例
     * @param accountId
     * @param machineId
     * @return
     */
    @Override
    public List<UserDivide> getAreaOrMachineDivide(Integer accountId, Integer machineId) {
        // 无订单欠款补交 逻辑 分到商户账号
        if (accountId == -1){
            return new ArrayList<>();
        }

        // 开启汇付 - 延时分账才走车辆分账 - 开启车辆分账
        // 根据区域id获取加盟商账号
        Account franchisee = accountService.getByAdAccountId(accountId);
        // 品牌id
        Integer brandId = franchisee.getParentId();
        // 是否实时分账
        boolean isCashAll = adaPayService.getPayType(brandId);
        AccountConfigExt accountConfigExt = cacheService.selectByAccountIdAndKey(accountId, AccountConfigExtConstant.MACHINE_DIVIDE_SWITCH);
        String paramValue = Optional.ofNullable(accountConfigExt).map(AccountConfigExt::getParamValue).orElse("0");
        // 是否开启车辆分账
        boolean isMachineDivide = Objects.equals("1",paramValue);

        // 开启分账 ， 延时分账 ， 开启车辆分账 = 才走车辆分账
        if (Objects.nonNull(machineId) && !isCashAll && isMachineDivide){
            Machine machine = machineService.getByMachineId(machineId);
            // 查询当前生效的车辆分账配置
            List<UserDivide> nowMachineDivides = getByMachineGroupIdAndState(machine.getMachineGroupId(), AdaPayConstant.ADAPAY_USER_DIVIDE_USED,accountId);
            List<UserDivide> willValidmachineDivides = userDivideDao.getByMachineGroupId(machine.getMachineGroupId(),accountId);
            // 存在 (达到生效时间但未生效) 的车辆分组分账配置
            if (!willValidmachineDivides.isEmpty()){
                // 应用新配置，当前配置需置为失效
                List<Integer> nowDivideIdList = new ArrayList<>();
                nowMachineDivides.forEach(divide -> nowDivideIdList.add(divide.getId()));
                // 将当前车辆分账生效配置 ， 置为失效
                userDivideDao.edit(new UserDivideVo(AdaPayConstant.ADAPAY_USER_DIVIDE_EXPIRE, StringUtil.getListString(nowDivideIdList)));

                // 将即将生效的车辆分账配置置为生效
                List<Integer> willValidDivideIdList = new ArrayList<>();
                willValidmachineDivides.forEach(divide -> willValidDivideIdList.add(divide.getId()));
                userDivideDao.edit(new UserDivideVo(AdaPayConstant.ADAPAY_USER_DIVIDE_USED, StringUtil.getListString(willValidDivideIdList)));
                return willValidmachineDivides;
            }else if (!nowMachineDivides.isEmpty()){    // 当前存在生效中的车辆分账配置
                return nowMachineDivides;
            }else { // 不存在 生效中和即将生效的车辆分账配置，走区域分账
                return getByAccountId(accountId);
            }
        }else {
            return getByAccountId(accountId);
        }
    }

    @Override
    public List<UserDivide> getByAccountIdAndState(Integer accountId, Integer state) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("state", AdaPayConstant.ADAPAY_USER_DIVIDE_USED);
        return userDivideDao.getByAccountIdAndState(map);
    }

    @Override
    public List<UserDivide> getByMachineGroupIdAndState(Integer machineGroupId, Integer state, Integer accountId) {
        Map<String, Object> map = new HashMap<>();
        map.put("machineGroupId",machineGroupId);
        map.put("state",state);
        map.put("accountId",accountId);
        return userDivideDao.getByMachineGroupIdAndState(map);
    }
}
